<script setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage, ElLoading, ElMessageBox, ElDialog, ElForm } from 'element-plus'
import servers from '@/utils/request.js'

// 可控变量
const select = ref('');
const input = ref('');

const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(24);

const placeholderText = ref('请选择查询条件');

const loading = ref('ture')

const value = ref('List')


// 查询
const search = () => {
  console.log(input.value);
  fetchData();
};

// 查询条件判断
const updatePlaceholder = () => {
  if (select.value === '1') {
    placeholderText.value = '请输入名称';
  } else if (select.value === '2') {
    placeholderText.value = '请输入码单编号';
  } else {
    placeholderText.value = '请选择查询条件';
  }
}

// 视图切换
const options = ref([
  {
    value: 'List',
    icon: 'Operation',
  },
  {
    value: 'Grid',
    icon: 'Menu',
  },
])

// 刷新页面
const refresh = async () => {
  loading.value = true;
  const loadingInstance = ElLoading.service({
    target: '.box_main',
    text: '正在刷新...',
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    await new Promise(resolve => setTimeout(resolve, 400));
    await fetchData();
    loadingInstance.close();
    loading.value = false;
    ElMessage({
      type: 'success',
      message: '刷新成功'
    });
  } catch (error) {
    loadingInstance.close();
    loading.value = false;
    ElMessage.error('刷新失败，请重试');
  }
}

// 获取数据列表
const fetchData = async () => {
  try {
    const response = await servers.get('/api/code/list', {
      params: {
        select: select.value,
        input: input.value,
        page: currentPage.value,
        limit: pageSize.value,
      },
    });
    if (response.data && response.data.success && response.data.data) {
      tableData.value = response.data.data.list;
      total.value = response.data.data.total;
      loading.value = false;
    } else {
      console.error('请联系管理员:', response.data);
    }
  } catch (error) {
    console.error('请联系管理员，获取数据失败，', error);
  }
};

// 更新分页器
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchData();
};

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除 ${row.name} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    }
  )
    .then(async () => {
      try {
        const response = await servers.delete(`/api/code/delete/${row.id}`)
        if (response.data.success) {
          ElMessage({
            type: 'success',
            message: response.data.message || '删除成功'
          })
          fetchData()
        } else {
          ElMessage.error(response.data.message || '删除失败')
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '删除失败，请重试')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

const editDialogVisible = ref(false)
const editForm = ref({
  name: '',
  type: '',
  id: null
})

const handleEdit = (row) => {
  editForm.value = {
    name: row.name,
    type: row.type,
    id: row.id
  }
  editDialogVisible.value = true
}

const submitEdit = async () => {
  try {
    const response = await servers.put(`/api/code/update/${editForm.value.id}`, editForm.value)
    if (response.data.success) {
      ElMessage({
        type: 'success',
        message: response.data.message || '编辑成功'
      })
      editDialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(response.data.message || '编辑失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '编辑失败，请重试')
  }
}

// 添加新的响应式变量
const uploadDialogVisible = ref(false)
const createFolderDialogVisible = ref(false)
const newFolderName = ref('')
const multipleSelection = ref([])
const uploadRef = ref(null)

// 处理文件上传
const handleFileUpload = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await servers.post('/api/code/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.success) {
      ElMessage({
        type: 'success',
        message: response.data.message || '上传成功'
      })
      fetchData()
    } else {
      ElMessage.error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '上传失败，请重试')
  }
}

// 文件上传前验证
const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('文件大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理文件选择
const handleFileChange = (uploadFile) => {
  if (beforeUpload(uploadFile.raw)) {
    handleFileUpload(uploadFile.raw)
  }
}

// 选择文件处理
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的文件')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${multipleSelection.value.length} 个文件吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    }
  )
    .then(async () => {
      try {
        const ids = multipleSelection.value.map(item => item.id)
        const response = await servers.delete('/api/code/batchDelete', { data: { ids } })
        if (response.data.success) {
          ElMessage({
            type: 'success',
            message: response.data.message || '批量删除成功'
          })
          fetchData()
        } else {
          ElMessage.error(response.data.message || '批量删除失败')
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '批量删除失败，请重试')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

// 新建文件夹
const createFolder = async () => {
  if (!newFolderName.value.trim()) {
    ElMessage.warning('请输入文件夹名称')
    return
  }

  try {
    const response = await servers.post('/api/code/createFolder', {
      name: newFolderName.value.trim()
    })
    if (response.data.success) {
      ElMessage({
        type: 'success',
        message: response.data.message || '创建成功'
      })
      createFolderDialogVisible.value = false
      newFolderName.value = ''
      fetchData()
    } else {
      ElMessage.error(response.data.message || '创建失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '创建失败，请重试')
  }
}

// 文件上传处理
const handleUploadSuccess = (response) => {
  if (response.success) {
    ElMessage({
      type: 'success',
      message: response.message || '上传成功'
    })
    fetchData()
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleUploadError = (error) => {
  ElMessage.error(error.message || '上传失败，请重试')
}

// 页面开始加载
onMounted(() => {
  fetchData();
});
watch(select, updatePlaceholder);
</script>

<template>
  <div class="list-container">
    <div class="bx header">
      <div class="box_left">
        <el-input v-model="input" :placeholder="placeholderText" clearable style="max-width: 300px;" maxlength="10"
          @keyup.enter="search">
          <template #prepend>
            <el-select v-model="select" placeholder="条件" style="width: 80px">
              <el-option label="品名" value="1" />
              <el-option label="编号" value="2" />
            </el-select>
          </template>
        </el-input>
        <el-button icon="Search" @click="search" type="primary" style="margin-left: 10px;" plain>查询</el-button>
      </div>
      <div class="box_right">
        <el-button icon="Refresh" type="info" plain @click="refresh" :loading="loading">刷新</el-button>
        <el-button icon="Delete" type="danger" plain @click="handleBatchDelete" 
          :disabled="multipleSelection.length === 0">批量删除</el-button>
        <el-button icon="UploadFilled" type="warning" plain @click="uploadDialogVisible = true">上传文件</el-button>
        <el-button icon="Plus" type="success" plain @click="createFolderDialogVisible = true">新建文件夹</el-button>
        <div class="custom-style">
          <el-segmented v-model="value" :options="options" size="small">
            <template #default="scope">
              <div class="self_add">
                <el-icon size="20">
                  <component :is="scope.item.icon" />
                </el-icon>
              </div>
            </template>
          </el-segmented>
        </div>
      </div>
    </div>

    <!-- 列表 -->
    <div v-show="value === 'List'" class="box_main">
      <el-table :data="tableData" v-loading="loading" :height="'calc(100vh - 180px)'">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="name" label="文件名"/>
        <el-table-column prop="size" label="大小" sortable width="200"/>
        <el-table-column prop="type" label="文件类型" width="200"/>
        <el-table-column prop="updatetime" label="修改时间" width="200"/>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)" style="margin-right: 10px">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 网格 -->
    <div v-show="value !== 'List'" class="box_main grid-container">
      <el-row :gutter="20">
        <el-col v-for="item in tableData" :key="item.id" :span="4">
          <el-card shadow="hover" class="grid-card">
            <div class="grid-item">
              <el-icon :size="40" :class="['file-icon', item.type === 'folder' ? 'folder-icon' : '']">
                <component :is="item.type === 'folder' ? 'Folder' : 'Document'" />
              </el-icon>
              <div class="file-name" :title="item.name">{{ item.name }}</div>
              <div class="file-info">
                <span class="size">{{ item.size }}</span>
                <span class="time">{{ item.updatetime }}</span>
              </div>
              <div class="operations">
                <el-button type="primary" size="small" @click="handleEdit(item)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(item)">
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="pagination-container">
      <el-pagination :current-page="currentPage" :page-size="pageSize" pager-count="10" background
        layout="jumper, prev, pager, next, total" :total="total" @current-change="handlePageChange" />
    </div>

    <el-dialog
      v-model="editDialogVisible"
      title="编辑文件"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="文件名">
          <el-input v-model="editForm.name" placeholder="请输入文件名"/>
        </el-form-item>
        <el-form-item label="文件类型">
          <el-select v-model="editForm.type" placeholder="请选择文件类型" style="width: 100%">
            <el-option label="文件夹" value="folder"/>
            <el-option label="文件" value="file"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="30%"
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        multiple
        :action="uploadConfig.action"
        :headers="uploadConfig.headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
      </el-upload>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog
      v-model="createFolderDialogVisible"
      title="新建文件夹"
      width="30%"
    >
      <el-form>
        <el-form-item label="文件夹名称">
          <el-input v-model="newFolderName" placeholder="请输入文件夹名称"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createFolderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createFolder">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.custom-style {
  float: right;
  margin-left: 10px;
}

.self_add {
  padding: .25rem;
  display: flex;
}

.custom-style .el-segmented {
  --el-segmented-bg-color: #485460;
  --el-segmented-color: #fff;
  --el-segmented-item-selected-color: var(--el-text-color-primary);
  --el-segmented-item-selected-bg-color: #ffd100;
}

.box_left :deep(.el-select__placeholder.is-transparent) {
  color: #485460;
}

div.bx {
  box-shadow: var(--el-box-shadow);
  border-radius: 4px;
  margin-bottom: 15px;
}

.header {
  display: flex;
  height: 45px;
  padding: 10px 10px 0;
  overflow: hidden;
  justify-content: space-between;
}

.box_left {
  flex: 1;
}

.box_right {
  float: right;
}


.grid-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: var(--el-transition-duration);
  border: none;
  border-radius: 10px;
}

.grid-card:hover {
  transform: translateY(-5px);
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  position: relative;
  padding-bottom: 50px;
}

.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border-radius: 15px;
  background: var(--el-color-primary-light-9);
  margin-bottom: 12px;
}

.file-icon {
  color: var(--el-color-primary);
}

.folder-icon {
  color: #ffd700;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  text-align: center;
}

.file-info {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.file-info .size {
  color: var(--el-color-info);
  background: var(--el-color-info-light-9);
  padding: 2px 8px;
  border-radius: 10px;
}


.list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  min-height: calc(100vh - 100px);
}

.box_main {
  flex: 1;
  overflow-y: auto;
}

.pagination-container {
  padding: 15px 0;
  display: flex;
  justify-content: center;
  border-top: 1px solid var(--el-border-color-lighter);
}

.operations {
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 10px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.grid-card:hover .operations {
  opacity: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-demo {
  text-align: center;
}

.el-upload__text {
  margin-top: 10px;
  color: #606266;
}

.el-upload__text em {
  color: var(--el-color-primary);
  font-style: normal;
}
</style>